import os
from datetime import datetime

from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import HttpResponse
from django.shortcuts import render, redirect

# Create your views here.
# djingo会把用户请求信息封装成对象，作为参数传入
from django.utils.decorators import method_decorator
from django.views import View

from django_study.settings import MEDIA_ROOT
from .form import ArticleForm
from .models import *


def test(request, *args, **kwargs):
    # print(kwargs)
    # info = kwargs.get("inf")
    # print(info)
    # print('text')
    user = User.objects.get(username='lisa')
    print(user.check_password('qwe123'))
    return HttpResponse(" 你好，django ")


def TV(request, *args, **kwargs):
    return HttpResponse("<h1 style='color:red;'> 你好，django </h1>")


data = {
    "python": [{
        'title': '机器学习：数据清洗与预处理 | Python',
        'desc': '我们不论在学习机器学习还是数据分析中，都会涉及很多数据。但原数据不可避免有很多杂志，为了确保结果的准确性，我们需要首先进行数据清洗和预处理。本文聚焦机器学习中的数据清洗与预处理。先阐述其重要性，如同为数据“大扫除”，能提升数据质量、保障结论可靠。接着分八个步骤详细讲解，从环境准备与库导入，到数据加载、初探，再到缺失值、重复值、异常值处理，以及数据类型转换和标准化/归一化，每个步骤都有代码示例和函数解释。最后以鸢尾花数据集为例实践，经各环节处理后保存清洗数据。',

        'detail': 'https://blog.csdn.net/2401_87533975/article/details/149427162',
        'img': 'https://i-blog.csdnimg.cn/direct/6573187aae9f46c9bda8c4d2d253d04b.jpeg',
        'creat_time': datetime(2025, 7, 14, 21, 4)
    },
        {
            'title': '深挖 DeepSeek 隐藏玩法·智能炼金术2.0版本',
            'desc': '还在用“帮我写个作文”这种简单的提问吗？学会用AI“听懂人话”的隐藏技巧，你学还是不学，如何让使用效率翻倍，让AI抓住重点？越具体的提问也并非是绝对有效的，看完此篇，让你从青铜玩家直达王者，内含几大神级提示词，90%的人都不知道！',
            'detail': 'https://blog.csdn.net/Dovis5884/article/details/146907730?spm=1000.2115.3001.10525',
            'img': 'https://i-blog.csdnimg.cn/direct/b6cab4b942714152851f2bd97cded5bf.gif',
            'creat_time': datetime(2025, 7, 16, 22, 4)
        }
    ],
    "java": [{
        'title': '机器学习：数据清洗与预处理 | Python',
        'desc': '我们不论在学习机器学习还是数据分析中，都会涉及很多数据。但原数据不可避免有很多杂志，为了确保结果的准确性，我们需要首先进行数据清洗和预处理。本文聚焦机器学习中的数据清洗与预处理。先阐述其重要性，如同为数据“大扫除”，能提升数据质量、保障结论可靠。接着分八个步骤详细讲解，从环境准备与库导入，到数据加载、初探，再到缺失值、重复值、异常值处理，以及数据类型转换和标准化/归一化，每个步骤都有代码示例和函数解释。最后以鸢尾花数据集为例实践，经各环节处理后保存清洗数据。',

        'detail': 'https://blog.csdn.net/2401_87533975/article/details/149427162',
        'img': 'https://i-blog.csdnimg.cn/direct/6573187aae9f46c9bda8c4d2d253d04b.jpeg',
        'creat_time': datetime(2024, 7, 14, 12, 4)
    }],
    "deepseek": []

}
user = {
    "name": "rose",
    "sex": "女"
}


# user = None
def nav(request, *args, **kwargs):
    # username = request.session.get('username')
    username = request.user.username
    classes = kwargs.get("classes")
    # print(classes)
    # res = data.get(classes)
    # if not res:
    #     # return redirect('/demo/404/')
    #     print(reverse('not_find'))
    #     return redirect('not_find')
    # return HttpResponse(f'文章数据{classes}分类下的{res}')
    # return HttpResponse(render(request,'demo/nav.html'))
    # if classes not in list(data.keys()):
    #     return redirect("not_find")
    try:
        res = Classes.objects.get(name=classes)
    except Classes.DoesNotExist:
        return redirect('not_find')
    return HttpResponse(render(request, 'demo/nav.html',
                               context={
                                   # "articles": res,
                                   "articles": res.article_set.all(),
                                   # "now_cls": classes,
                                   "now_cls": classes,
                                   # "classes": data.keys(),
                                   "classes": Classes.objects.all(),
                                   "username": username
                               }))


def not_find(request, **kwargs):
    print(kwargs)
    return HttpResponse('该页面不存在，小主走错路了')


def index(request, **kwargs):
    # print(kwargs)
    # print(request)
    # username = request.session.get('username')
    username = request.user.username
    return HttpResponse(render(request, 'demo/index.html', context={
        # "classes": data.keys(),
        "classes": Classes.objects.all(),
        # "user": user
        "username": username
    }))


def classes(request, **kwargs):
    # classes1 = Classes(name="python")
    # # classes1.save()
    # classes2=Classes()
    # classes2.name='java'
    # classes2.save()
    #
    # res1=Classes.objects.create(name='deepseek')
    # print(res1)
    # # Classes.objects.get_or_create(name='html')
    # # res= Classes.objects.all()
    # # print(res)
    # res2 = Classes.objects.get(c)
    # print(res2)
    # res3= Classes.objects.filter(name='deepseek')
    # print(res3)
    # res=Classes.objects.get(name='java')
    # res.name="JAVA"
    # res.save()
    # Classes.objects.filter(name="deepseek").update(name="DeepSeek")
    # res5 = Classes.objects.get(name='DeepSeek')
    # res5.delete()

    # 查询方式
    # print(Classes.objects.first())
    # print(Classes.objects.first())
    # print(Classes.objects.exclude(name='python'))
    # print(Classes.objects.order_by('id'))
    # print(Classes.objects.order_by('-id'))
    # #
    # # # 查询条件
    # print(Classes.objects.get(name__iexact='python'))
    # print(Classes.objects.filter(name__contains='t'))
    # print(Classes.objects.filter(name__startswith='d'))
    # print(Classes.objects.filter(name__endswith='d'))
    # print(Classes.objects.filter(name__in=['python', 'DeepSeek']))
    #
    # # # 根据数字
    # print(Classes.objects.filter(id__gt=2))
    # print(Classes.objects.filter(id__gte=4))
    # print(Classes.objects.filter(id__lt=7))
    # print(Classes.objects.filter(id__lte=6))
    # print(Classes.objects.filter(id__range=(3, 6)))
    # print(Classes.objects.filter(name__isnull=False))

    return HttpResponse('数据更新成功')


def tab_info(request, **kwargs):
    # user=User(username='rose')
    # user.set_password('qwe123')
    # user.save()
    # UserDetail.objects.create(age=18,sex=0,user_id=2)
    Article.objects.create(tiltle='text111', desc='text-111', content='', classes_id=2, user_id=1)
    Article.objects.create(tiltle='text222', desc='text-222', content='', classes_id=2, user_id=1)

    return HttpResponse('成功')


#
class AddArticleView(View):
    @method_decorator(login_required)
    def get(self, request):
        form = ArticleForm()
        # user = request.session.get('username')
        user = request.user.username
        return render(request, 'demo/add_article.html', context={'username': user, 'form': form})

    def post(self, request):
        form = ArticleForm(request.POST, request.FILES)

        user = request.user.username
        if form.is_valid():
            title = form.cleaned_data.get('title')
            desc = form.cleaned_data.get('desc')
            content = form.cleaned_data.get('content')
            cover = form.cleaned_data.get('cover')
            classes = form.cleaned_data.get('classes')
            labels = form.cleaned_data.get('label')
            user = request.user
            file_name = f'{datetime.now().strftime("%y%m%d%H%M%S")}_{cover.name}'
            print(cover)
            print(labels)
            with open(os.path.join(MEDIA_ROOT, file_name), 'wb') as fp:
                for date in cover.chunks():
                    fp.write(date)

            article = Article.objects.create(title=title, desc=desc, content=content, cover=file_name, user=user,
                                             classes=classes)
            for i in labels:
                article.label.add(i)

        return render(request, 'demo/add_article.html', context={'user': user, 'form': form})


class ArticleDetailView(View):
    def get(self, request, id):
        user = request.user.username
        try:
            article = Article.objects.get(id=id)
        except Article.DoesNotExist:
            return redirect('not_find')
        return render(request, 'demo/article_detail.html',
                      context={'article': article, 'labels': article.label.all(), 'username': user})


class ArticleUserView(View):
    @method_decorator(login_required)
    def get(self, request):
        article = Article.objects.filter(user=request.user)
        pg = Paginator(article, 5)
        try:
            pg_current = request.GET.get('page')
            pages = pg.page(pg_current)
        except PageNotAnInteger:
            pages = pg.page(1)
        except EmptyPage:
            pages = pg.page(pg.num_pages)
        return render(request, 'demo/user_article.html',
                      context={'username': request.user.username, 'articles': article, 'pages': pages})


class ArticleUpdateView(View):
    def get(self, request, id):

        try:
            article = Article.objects.get(id=id)
        except Article.DoesNotExist:
            return redirect('not_find')
        else:
            data = {
                "title": article.title,
                "desc": article.desc,
                "content": article.content,
                "classes": article.classes,
                "label": article.label.all(),
            }

            form = ArticleForm(data)

        return render(request, 'demo/update_article.html',
                      context={'username': request.user.username, 'form': form})

    def post(self, request, id):
        form = ArticleForm(request.POST, request.FILES)

        user = request.user.username
        if form.is_valid():
            title = form.cleaned_data.get('title')
            desc = form.cleaned_data.get('desc')
            content = form.cleaned_data.get('content')
            cover = form.cleaned_data.get('cover')
            classes = form.cleaned_data.get('classes')
            labels = form.cleaned_data.get('label')
            user = request.user
            file_name = f'{datetime.now().strftime("%y%m%d%H%M%S")}_{cover.name}'

            with open(os.path.join(MEDIA_ROOT, file_name), 'wb') as fp:
                for date in cover.chunks():
                    fp.write(date)
            articles = Article.objects.filter(id=id)
            os.remove(os.path.join(MEDIA_ROOT, articles[0].cover))

            articles.update(title=title, desc=desc, content=content, cover=file_name, user=user,
                            classes=classes)
            articles[0].label.clear()
            for i in labels:
                articles[0].label.add(i)

        return render(request, 'demo/update_article.html',
                      context={'form': form})


class ArticleDeleteView(View):
    def get(self, request, id):
        try:
            article=Article.objects.get(id=id)
        except Article.DoesNotExist:
            return redirect('not_find')
        try:
            os.remove(os.path.join(MEDIA_ROOT,article.cover))
        except:FileNotFoundError
            
        article.delete()
        return redirect('ArticleUser')
